package com.lhh.myspringboot.utils;

import com.lhh.myspringboot.bean.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.SmartInitializingSingleton;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

public class HtmlParseUtil {

    public static void main(String[] args) throws IOException {


        HtmlParseUtil.parseJD("java").forEach(System.out::println);


    }

    public static ArrayList<Content> parseJD(String keywords) throws IOException{
        String url = "https://search.jd.com/Search?keyword=" + keywords+"&enc=utf-8&wq=" + keywords+ "&pvid=03b0a7f29af64840a06249a3936b9ad4";

        // 解析网页 Jsoup返回document就是浏览器document对象
        Document document = Jsoup.parse(new URL(url), 30000);

        Element element = document.getElementById("J_goodsList");
        //System.out.println(element.html());

        Elements li = element.getElementsByTag("li");

        ArrayList<Content> contents = new ArrayList<>();
        for (Element el : li) {
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String tittle = el.getElementsByClass("p-name").eq(0).text();

            System.out.println("======================================");
            System.out.println(img);
            System.out.println(price);
            System.out.println(tittle);

            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTittle(tittle);
            contents.add(content);
        }

        return contents;
    }
}
